package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.service.UploadService;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.IMaiHaoWanApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;

@Slf4j
@Service
public class MaiHaoWanApiImpl implements IMaiHaoWanApi {

    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private UploadService uploadService;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    private ArtRecMapper artRecMapper;


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        pdObject(goodsInfoAndAttrValueDto, salePartner);
        Map<String, Object> params = new HashMap<>();
        if ("王者荣耀".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 443);
            switch (goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName()) {
                case "安卓QQ":
                    params.put("zone_id", 7717);
                    params.put("server_id", 7718);
                    params.put("phone_type", 1);
                    break;
                case "安卓微信":
                    params.put("zone_id", 9419);
                    params.put("server_id", 9420);
                    params.put("phone_type", 1);
                    break;
                case "苹果QQ":
                    params.put("zone_id", 7720);
                    params.put("server_id", 7721);
                    params.put("phone_type", 2);
                    break;
                case "苹果微信":
                    params.put("zone_id", 9566);
                    params.put("server_id", 9567);
                    params.put("phone_type", 2);
                    break;
            }
        } else if ("和平精英".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 683);
            switch (goodsInfoAndAttrValueDto.getSystemName() + goodsInfoAndAttrValueDto.getCarrierName()) {
                case "安卓QQ":
                    params.put("zone_id", 8167);
                    params.put("server_id", 8168);
                    params.put("phone_type", 1);
                    break;
                case "安卓微信":
                    params.put("zone_id", 9421);
                    params.put("server_id", 9422);
                    params.put("phone_type", 1);
                    break;
                case "苹果QQ":
                    params.put("zone_id", 8167);
                    params.put("server_id", 8168);
                    params.put("phone_type", 2);
                    break;
                case "苹果微信":
                    params.put("zone_id", 9421);
                    params.put("server_id", 9422);
                    params.put("phone_type", 2);
                    break;
            }
        } else if ("英雄联盟".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 17);
            String quanfu = "[{\"id\":11907,\"name\":\"联盟五区\",\"server_list\":[{\"id\":60,\"name\":\"巨龙之巢\"},{\"id\":58,\"name\":\"恕瑞玛\"},{\"id\":57,\"name\":\"无畏先锋\"},{\"id\":55,\"name\":\"德玛西亚\"}]},{\"id\":11906,\"name\":\"联盟四区\",\"server_list\":[{\"id\":59,\"name\":\"扭曲丛林\"},{\"id\":56,\"name\":\"弗雷尔卓德\"},{\"id\":54,\"name\":\"比尔吉沃特\"}]},{\"id\":11905,\"name\":\"联盟三区\",\"server_list\":[{\"id\":48,\"name\":\"水晶之痕\"},{\"id\":45,\"name\":\"皮城警备\"},{\"id\":38,\"name\":\"钢铁烈阳\"},{\"id\":37,\"name\":\"裁决之地\"},{\"id\":36,\"name\":\"班德尔城\"}]},{\"id\":11904,\"name\":\"联盟二区\",\"server_list\":[{\"id\":51,\"name\":\"征服之海\"},{\"id\":50,\"name\":\"战争学院\"},{\"id\":44,\"name\":\"诺克萨斯\"},{\"id\":43,\"name\":\"雷瑟守备\"},{\"id\":42,\"name\":\"卡拉曼达\"},{\"id\":35,\"name\":\"暗影岛\"}]},{\"id\":11903,\"name\":\"联盟一区\",\"server_list\":[{\"id\":7683,\"name\":\"男爵领域\"},{\"id\":7256,\"name\":\"教育网专区\"},{\"id\":52,\"name\":\"祖安\"},{\"id\":49,\"name\":\"影流\"},{\"id\":47,\"name\":\"守望之海\"},{\"id\":46,\"name\":\"皮尔特沃夫\"},{\"id\":41,\"name\":\"均衡教派\"},{\"id\":40,\"name\":\"巨神峰\"}]},{\"id\":11902,\"name\":\"峡谷之巅\",\"server_list\":[{\"id\":7745,\"name\":\"峡谷之巅\"}]},{\"id\":11901,\"name\":\"黑色玫瑰\",\"server_list\":[{\"id\":39,\"name\":\"黑色玫瑰\"}]},{\"id\":11900,\"name\":\"艾欧尼亚\",\"server_list\":[{\"id\":34,\"name\":\"艾欧尼亚\"}]}]\n";
            JSONArray jsonArray = JSONArray.parseArray(quanfu);
            for(Object o : jsonArray){
                String server_list = JSONObject.parseObject(o.toString()).getString("server_list");
                JSONArray jsonArray1 = JSONArray.parseArray(server_list);
                for(Object p : jsonArray1){
                    if(goodsInfoAndAttrValueDto.getServerName().equals(JSONObject.parseObject(p.toString()).getString("name"))){
                        params.put("zone_id", JSONObject.parseObject(o.toString()).getString("id"));
                        params.put("server_id", JSONObject.parseObject(p.toString()).getString("id"));
                        break;
                    }
                }
            }
            params.put("phone_type", 1);
        } else if ("穿越火线".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 11);
            String quandaqu = "北京四区=447--442, 辽宁一区=453--442, 吉林一区=452--442, 辽宁二区=454--442, 山东二区=457--442, " +
                    "辽宁三区=455--442, 北京三区=446--442, 山东一区=456--442, 河南一区=449--442, 黑龙江区=451--442, 河北一区=448--442, " +
                    "北京二区=445--442, 北京一区=444--442, 山西一区=458--442, 北方大区=443--442, 河南二区=450--442,浙江二区=440--417, " +
                    "安徽一区=418--417, 上海二区=435--417, 湖南二区=428--417, 江苏二区=430--417, 湖北二区=426--417, 广东二区=421--417, " +
                    "湖南一区=427--417, 湖北一区=425--417, 广东一区=420--417, 广西一区=424--417, 广东四区=423--417, 云南一区=438--417, " +
                    "预备大区=8486--417, 南方大区=432--417, 重庆一区=441--417, 陕西一区=433--417, 江西一区=431--417, 广东三区=422--417, " +
                    "江苏一区=429--417, 浙江一区=439--417, 四川二区=437--417, 福建一区=419--417, 四川一区=436--417, 上海一区=434--417," +
                    "全区全服=463--462,移动专区=461--459, 教育网专区=460--459";
            Map qdqMap = stringTOmap(quandaqu.replace(" ",""));
            if (Objects.nonNull(qdqMap.get(goodsInfoAndAttrValueDto.getServerName()))) {
                String qu = qdqMap.get(goodsInfoAndAttrValueDto.getServerName()).toString();
                params.put("zone_id", qu.split("--")[1].trim());
                params.put("server_id", qu.split("--")[0].trim());
                params.put("phone_type", 1);
            } else {
                throw new GlobalException(goodsInfoAndAttrValueDto.getId() + "英雄联盟大区未找到");
            }
        } else if ("原神".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 1028);
            params.put("zone_id", 9465);
            params.put("server_id", 9466);
            params.put("phone_type", 1);
        } else if ("枪战王者".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 446);
            switch (goodsInfoAndAttrValueDto.getCarrierName()) {
                case "QQ":
                    params.put("zone_id", 7458);
                    params.put("server_id", 7475);
                    params.put("phone_type", 1);
                    break;
                case "微信":
                    params.put("zone_id", 9401);
                    params.put("server_id", 9402);
                    params.put("phone_type", 1);
                    break;
            }
        } else if ("火影忍者".equals(goodsInfoAndAttrValueDto.getGameName())) {
            params.put("game_id", 560);
            switch (goodsInfoAndAttrValueDto.getCarrierName()) {
                case "QQ":
                    params.put("zone_id", 7571);
                    params.put("server_id", 7573);
                    params.put("phone_type", 1);
                    break;
                case "微信":
                    params.put("zone_id", 9433);
                    params.put("server_id", 9434);
                    params.put("phone_type", 1);
                    break;
            }
        } else {
            throw new GlobalException("暂未对接买号玩接口此游戏：" + goodsInfoAndAttrValueDto.getGameName());
        }
        params = addOrEditParams(goodsInfoAndAttrValueDto, params, 1, salePartner);  // 1 表示是新增
        params = params(params, salePartner);
        log.info("买号玩新增请求参数{}"+JSONObject.toJSONString(params));
        String zhfb = "/Channel/Account/addAccount"; // 账号发布接口
//        String response = HttpUtils.sendPost(salePartner.getTwoOther() + zhfb,
//                StringEscapeUtils.unescapeJava(JSONObject.toJSONString(params).replaceAll("\\s*", "")).replaceAll("\n" +
//                        "|\t", ""), "UTF-8");
        String response = HttpRequest.post(salePartner.getTwoOther() + zhfb).body(JSONObject.toJSONString(params).replaceAll("\\s*", "")).execute().body();
        JSONObject resultJson = JSONObject.parseObject(response);
        log.info("买号玩新增返回参数{}"+resultJson);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            JSONObject res = resultJson.getJSONObject("result");
            String reaccount_id = res.getString("account_id");
            result.put("outId", reaccount_id);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("result"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Long account_id = ReMHWId(goodsInfoAndAttrValueDto, salePartner);
        Map<String, Object> params = new HashMap<>();
        params.put("account_id", account_id);
        if ("王者荣耀".equals(goodsInfoAndAttrValueDto.getGameName())||"和平精英".equals(goodsInfoAndAttrValueDto.getGameName())||"火影忍者".equals(goodsInfoAndAttrValueDto.getGameName())) {
            switch (goodsInfoAndAttrValueDto.getSystemName()) {
                case "安卓":
                    params.put("phone_type", 1);
                    break;
                case "苹果":
                    params.put("phone_type", 2);
                    break;
            }
        } else if ("英雄联盟".equals(goodsInfoAndAttrValueDto.getGameName())) {
//            params.put("phone_type",1);
        } else if ("穿越火线".equals(goodsInfoAndAttrValueDto.getGameName())) {
//            params.put("phone_type",1);
        } else if ("原神".equals(goodsInfoAndAttrValueDto.getGameName())) {
//            params.put("phone_type",1);
        }
        params = addOrEditParams(goodsInfoAndAttrValueDto, params, 2, salePartner); // 2 表示修改
        params = params(params, salePartner);
        String zhxg = "/Channel/Account/editAccount"; //账号修改接口
        String response = HttpUtils.sendPost(salePartner.getTwoOther() + zhxg,
                StringEscapeUtils.unescapeJava(JSONObject.toJSONString(params).replaceAll("\\s*", "")).replaceAll("\n" +
                        "|\t", ""), "UTF-8");
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("result"));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Long account_id = ReMHWId(goodsInfoAndAttrValueDto, salePartner);
        Map<String, Object> params = new HashMap<>();
        params.put("account_id", account_id);
        params = params(params, salePartner);
        String zhsc = "/Channel/Account/delAccount";// 账号删除接口
        String response = HttpUtils.sendPost(salePartner.getTwoOther() + zhsc,
                StringEscapeUtils.unescapeJava(JSONObject.toJSONString(params).replaceAll("\\s*", "")).replaceAll("\n" +
                        "|\t", ""), "UTF-8");
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            artRecMapper.deleteArtRecCode(goodsInfoAndAttrValueDto.getId(), salePartner.getId());
        }
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("result"));

        return AjaxResult.success(result);
    }

    /**
     * 返回MHWId
     *
     * @param goodsInfoAndAttrValueDto
     * @param salePartner
     * @return
     */

    private Long ReMHWId(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        pdObject(goodsInfoAndAttrValueDto, salePartner);
        Long MHWid;
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(artRecs)) {
            if (artRecs.size() == 1) {
                MHWid = Long.parseLong(artRecs.get(0).getOutid());
            } else {
                throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                        "下的对应的MHWid有多个");
            }
        } else {
            throw new GlobalException("商品id为 " + goodsInfoAndAttrValueDto.getId() + " 在供应商id为" + salePartner.getId() +
                    "下未找到MHWid");
        }
        return MHWid;
    }

    /**
     * 判断 goodsInfoAndAttrValueDto salePartner 实体是否为空
     *
     * @param goodsInfoAndAttrValueDto
     * @param salePartner
     */
    private void pdObject(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        if (Objects.isNull(goodsInfoAndAttrValueDto)) {
            throw new GlobalException("商品信息对象为空");
        }
        if (Objects.isNull(salePartner)) {
            throw new GlobalException("伙伴对象为空");
        }
    }

    /**
     * 封装 添加和修改账号的的公共参数
     *
     * @param goodsInfoAndAttrValueDto
     * @param params
     * @return
     */
    private Map<String, Object> addOrEditParams(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String,
            Object> params, int type, SalePartner sa) {
        String imgs = "";
        if (Objects.nonNull(goodsInfoAndAttrValueDto.getTitleImg())) {
            String titleImgUrl = goodsInfoAndAttrValueDto.getTitleImg();
//            titleImgUrl = formatImgUrl(titleImgUrl); // 截取 “？” 之前的字符串并返回
//            titleImgUrl = toCoverImg(titleImgUrl);
            if (!pdhouzhui(titleImgUrl)) {
                throw new GlobalException("标题图片的后缀或无后缀接口不支持");
            }
            imgs = titleImgUrl + "|";
        }
        GoodsInfoImg infoImg = new GoodsInfoImg();
        infoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        infoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(infoImg);
        if(infoImgs.size()>90){
            infoImgs = infoImgs.subList(0,90);
        }
        if (!CollectionUtils.isEmpty(infoImgs)) {
            for (GoodsInfoImg img : infoImgs) {
                String imgurl = img.getImgUrl();
                if (!pdhouzhui(imgurl)) {
                    throw new GlobalException("附件图片的后缀或无后缀接口不支持");
                }
                imgs = imgs + img.getImgUrl() + "|";
            }
            imgs = imgs.substring(0, imgs.length() - 1);
        } else {
            imgs = imgs + LCConstant.defaultImg;
        }
        params.put("img_url", imgs);

        String title = goodsInfoAndAttrValueDto.getDes();
        if (Objects.nonNull(title)) {
            if (title.length() > 100) {
                title = title.substring(0, 90);
            }
            params.put("title", title);  // 商品标题 怎么取值   截取des
        } else {
            params.put("title", "默认标题");
        }
        //1.未实名，2：已实名可更改，3：已实名不可更改
        int level = 30;
        int shiming = 3;
        if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "王者荣耀")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF1())) {
                level = Integer.parseInt(goodsInfoAndAttrValueDto.getF1());
            }
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF13())) {
                if (Integer.parseInt(goodsInfoAndAttrValueDto.getF13()) <= 200) {
                    params.put("inscription", goodsInfoAndAttrValueDto.getF13());
                } else {
                    params.put("inscription", 200);
                }
            }
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF7())) {
                params.put("yx", goodsInfoAndAttrValueDto.getF7());
            }
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF8())) {
                params.put("pf", goodsInfoAndAttrValueDto.getF8());
            }
            String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF16());
            if (StringUtils.equals("可二次实名", smFN)) {
                shiming = 2;
            } else if (StringUtils.equals("已删实名", smFN)) {
                shiming = 1;
            } else if (StringUtils.equals(smFN, "包人脸")) {
                shiming = 3;
            }
        } else if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "和平精英")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF16())) {
                String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF16());
                if (StringUtils.equals(smFN, "可二次实名")) {
                    shiming = 2;
                } else if (StringUtils.equals(smFN, "已删实名")) {
                    shiming = 1;
                } else if (StringUtils.equals(smFN, " 不可二次实名") || StringUtils.equals(smFN, " 包人脸")) {
                    shiming = 3;
                }
            }
        } else if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "英雄联盟")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF3())) {
                params.put("yx", goodsInfoAndAttrValueDto.getF3());
            }
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF4())) {
                params.put("pf", goodsInfoAndAttrValueDto.getF4());
            }
            String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF1());
            if (StringUtils.contains(smFN, "有修改人脸机会")) {
                shiming = 2;
            } else if (StringUtils.equals(smFN, "已删人脸实名可随时认证")) {
                shiming = 1;
            }
        } else if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "穿越火线")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF3())) {
                String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF3());
                if (StringUtils.contains(smFN, "有修改机会")) {
                    shiming = 2;
                } else if (StringUtils.equals(smFN, "已删实名")) {
                    shiming = 1;
                }
            }
        } else if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "原神")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF7())) {
                level = Integer.parseInt(goodsInfoAndAttrValueDto.getF7());
            }
            String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF20());
            if (StringUtils.contains(smFN, "有修改人脸机会") || StringUtils.equals(smFN, "可修改邮箱")) {
                shiming = 2;
            } else if (StringUtils.equals(smFN, "已删人脸实名可随时认证") || StringUtils.equals(smFN, "未绑定邮箱")) {
                shiming = 1;
            }
        } else if (StringUtils.equals(goodsInfoAndAttrValueDto.getGameName(), "枪战王者")) {
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF1())) {
                level = Integer.parseInt(goodsInfoAndAttrValueDto.getF1());
            }
            //实名 y
            if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF10())) {
                String smFN = reRedioValue(goodsInfoAndAttrValueDto.getF10());
                if (StringUtils.contains(smFN, "有修改人脸机会")) {
                    shiming = 2;
                } else if (StringUtils.equals(smFN, "已删人脸实名可随时认证")) {
                    shiming = 1;
                }
            }
        }
        params.put("level", level);
        params.put("is_auth_account", shiming);
        if (type == 1) {  //add账号需要字段  写死的值 账号修改 不需要再重复请求
            params.put("account_type", 2); // 账号类型，1：初始号，2：成品号
            params.put("role_name", "问客服");   //角色名称  怎么取值  问客服
            params.put("pwd", "111111");//游戏密码  固定111111
            params.put("bind_phone", 1);//绑定手机，0:未绑定，1：绑定
            params.put("bind_qa", 1);//绑定问题，0:未绑定，1：绑定
            params.put("bind_idcard", 1);//绑定身份证，0:未绑定，1：绑定
            params.put("xy_score", 500);//信誉积分值  500
            params.put("credit_score_lol", 120);//英雄联盟专属-信誉积分值1-120
            params.put("contact_way", "18888888888"); //紧急联系手机号码
            params.put("contact_qq", "111111111");//紧急联系QQ
        }
        params.put("zh", String.valueOf(System.currentTimeMillis()).substring(4)); //游戏账号  xyr+id
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal, goodsInfoAndAttrValueDto.getId(), sa);
        params.put("price", new DecimalFormat("0.##").format(bigDecimal)); //商品价格  怎么取值
        String des = goodsInfoAndAttrValueDto.getDes();
        if (StringUtils.isNotNull(des)) {
            if (des.length() > 490) {
                des = des.substring(0, 490);
            }
        }
        params.put("intro", des); // 商品描述  怎么取值 xyr+id+accountInfo.getDes()
        params.put("expiry_day", 60);//有效期天数，30/60/90选其一
        return params;
    }

    /**
     * 封装全局参数 app_id timestamp sign
     *
     * @param params
     * @param salePartner
     * @return
     */
    private Map<String, Object> params(Map<String, Object> params, SalePartner salePartner) {
        int app_id = Integer.parseInt(salePartner.getSaleKey());
        String appsecret = salePartner.getOther();
        params.put("app_id", app_id);
        int time = (int) (DateUtils.getNowDate().getTime() / 1000);
        params.put("timestamp", time);
        String cover1 = getCover(params);
        cover1 = cover1 + "appsecret=" + appsecret;
        String sign = DigestUtils.md5Hex(cover1);
        params.put("sign", sign);
        return params;
    }

    public String getCover(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        TreeSet<String> sortSet = new TreeSet<>(params.keySet()); //排序
        for (String key : sortSet) {
            if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(String.valueOf(params.get(key)))) {
                String val = params.get(key).toString();
                val = val.replaceAll("\\s*", "");
//                val = StringEscapeUtils.unescapeJava(val);
                val = val.replaceAll("\n|\t", "");
                val = HttpUtil.urlEncode(val, "utf-8");
                val = val.replaceAll("%2A", "*");

                resut.append(key + "=" + val + "&");
            }
        }
        return resut.toString();
    }

    public Map stringTOmap(String b) {
        Map docType = new HashMap();
        StringTokenizer items;
        for (StringTokenizer entrys = new StringTokenizer(b, ","); entrys.hasMoreTokens();
             docType.put(items.nextToken(), items.hasMoreTokens() ? ((Object) (items.nextToken())) : null)) {
            items = new StringTokenizer(entrys.nextToken(), "=");
        }
        return docType;
    }

    /**
     * 判断imgUrl里是否包含图片后缀
     *
     * @param str
     * @return
     */
    public boolean pdhouzhui(String str) {
        String image = str.substring(str.lastIndexOf(".") + 1).toLowerCase();
        String houzhui[] = {"jpeg", "jpg", "png", "gif", "webp", "bmp", "ico", ".tif"};
        return Arrays.asList(houzhui).contains(image);
    }

    /**
     * 截取imgUrl  “？” 之前的字符串
     *
     * @param imgUrl
     * @return
     */
    public String formatImgUrl(String imgUrl) {
        if (imgUrl.contains("?")) {
            imgUrl = imgUrl.substring(0, imgUrl.indexOf("?"));
        }
        return imgUrl;
    }

    private String reRedioValue(String value) {
        String reStr = "";
        if (StringUtils.isNotEmpty(value)) {
            GameAttribute gameAttribute =
                    gameAttributeService.selectGameAttributeById(Long.valueOf(value));
            if (gameAttribute != null) {
                if (StringUtils.isNotEmpty(gameAttribute.getFieldName())) {
                    reStr = gameAttribute.getFieldName();
                }

            }
        }
        return reStr;
    }

    public static void getYxlb() {
        Map<String, Object> params = new HashMap<>();
        params = params(null, params);
        String response = HttpUtils.sendPost(url + yxlb, JSONObject.toJSONString(params), "UTF-8");
        System.out.println("返回的response=" + response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String msg = jsonObject.getString("msg");
        String code = jsonObject.getString("code");
        JSONArray result = jsonObject.getJSONArray("result");
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map zh = new HashMap<>();
        for (Object o : result) {
            Map fuwuliebiao = new HashMap<>();
            String s = JSONObject.toJSONString(o);
            JSONObject jsonObject1 = JSONObject.parseObject(s);
            fuwuliebiao.put("id", jsonObject1.getString("id"));
            fuwuliebiao.put("name", jsonObject1.getString("name"));
            zh.put(jsonObject1.getString("name"), jsonObject1.getString("id"));
            resultList.add(fuwuliebiao);
        }
    }

    public static void getYxqf(int gameid) {
        int game_id = gameid;
        Map<String, Object> params = new HashMap<>();
        params.put("game_id", game_id);
        params = params(null, params);
        String response = HttpUtils.sendPost(url + yxqf, JSONObject.toJSONString(params), "UTF-8");
        System.out.println("返回的response=" + response);
    }

    private static Map<String, Object> params(AccountInfo accountInfo, Map<String, Object> params) {
        int app_id = 1000500000;
        String appsecret = "MNA63JBLCMATAVD577ZUV3AQ3RAAC7UC";
        params.put("app_id", app_id);
        int time = (int) (DateUtils.getNowDate().getTime() / 1000);
        params.put("timestamp", time);
        String cover1 = getCovertest(params);
        cover1 = cover1 + "appsecret=" + appsecret;
        System.out.println(cover1);
        String sign = DigestUtils.md5Hex(cover1);
        params.put("sign", sign);
        System.out.println("角色列表请求参数=" + JSONObject.toJSONString(params));
        return params;
    }

    public static String getCovertest(Map<String, Object> params) {
        StringBuffer resut = new StringBuffer();
        TreeSet<String> sortSet = new TreeSet<>(params.keySet()); //排序
        for (String key : sortSet) {
            if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(String.valueOf(params.get(key)))) {
                String val = params.get(key).toString();
                val = val.replaceAll("\\s*", "");
                val = HttpUtil.urlEncode(val, "utf-8");
                val = val.replaceAll("%2A", "*");
                resut.append(key + "=" + val + "&");
            }
        }
        return resut.toString();
    }


    private String toCoverImg(String imgUrl){
        //1、判断图片是否存在.jpg 或者 .png  .JPG .PNGu
        //2、不存在开始解析上传七牛云
        //3、返回地址

        boolean b = false;
        String imgStr = cn.hutool.http.HttpUtil.get(imgUrl + "?imageInfo");
        JSONObject jsonObject = JSONObject.parseObject(imgStr);
        Long size = jsonObject.getLong("size");
        if (size < 50000000l){
            b = true;
        }

        if (!(imgUrl.contains(".jpg") || imgUrl.contains(".png") || imgUrl.contains(".JPG") || imgUrl.contains(".PNG")) && StringUtils.isNotEmpty(imgUrl) || b){
            URL url = null;
            try {
                url = new URL(imgUrl);
                BufferedImage image = ImageIO.read(url.openStream());
                byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
                return uploadService.upload2Qiniu(bytes, "mhw/" + UUIDGenerator.generate()+".jpg");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return imgUrl;

    }

    static String url = "http://maihaowan.zuhaowan.net";
    static String yxlb = "/Channel/Account/getGameList"; //获取游戏列表信息
    static String yxqf = "/Channel/Account/getGameServerList"; //获取游戏区服信息
    static String zhfb = "/Channel/Account/addAccount"; // 账号发布接口
    static String zhxg = "/Channel/Account/editAccount"; //账号修改接口
    static String zhsc = "/Channel/Account/delAccount";// 账号删除接口
    static String a = "{王者荣耀=443, 逆战=24, QQ飞车(手游)=636, 崩坏3=664, 球球大作战=449, Nba2Kol2=761, 梦三国=28, 侠盗猎车手Online=441, " +
            "穿越火线=11, 糖豆人=1020, 绝地求生=581, 英雄联盟=17, 枪战王者=446, 人类一败涂地=673, 火影忍者（手游）=560, 原神（手游）=1028, 和平精英=683, " +
            "QQ炫舞手游=679, 三国杀手游=699, 使命召唤19：现代战争2=1427, 部落冲突=565, YY号码=23, 蛋仔派对=1117}";

    public static void main(String[] args) {
//        getYxlb();
        getYxqf(17);
//        String imgUrl = "https://images.pxb7.com/images/upload/image/20220723/20220723024502_197757
//        .jpg?x-oss-process=style/no-shuiyin";
//        imgUrl=formatImgUrl(imgUrl);
//        System.out.println(imgUrl);
//        String image = imgUrl.substring(imgUrl.lastIndexOf(".") + 1).toLowerCase();
//        System.out.println(image);
//        String houzhui[] = {"jpeg", "jpg", "png", "gif", "webp", "bmp", "ico"};
//        System.out.println(Arrays.asList(houzhui).contains(image));
    }
}
